from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QHBoxLayout, \
    QTextEdit, QComboBox, QSpacerItem, QSizePolicy
from PyQt6.QtCore import Qt, pyqtSignal, QObject
import cv2
import numpy as np
from PyQt6.QtWidgets import (QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout,
                             QMessageBox, QDialog, QCheckBox, QHBoxLayout, QGridLayout, QTimeEdit, QMainWindow,
                             QTextEdit, QToolBar,QScrollArea)
from PyQt6.QtCore import Qt,QDateTime,QTimer
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key
import sys,openpyxl
import pandas as pd  # 用于读取CSV文件
from PyQt6.QtWidgets import QMainWindow, QApplication, QMenuBar, QToolBar, QStatusBar, QTextEdit, QLabel, \
    QVBoxLayout, QWidget, QFileDialog, QMessageBox, QMenu, QDialog,QComboBox,QSplitter
from PyQt6.QtGui import QIcon, QPixmap,QAction,QImage
from PyQt6.QtCore import QDateTime, QTimer, Qt

class Communicator(QObject):
    message_signal = pyqtSignal(str)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('云资源管理平台主页')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()

    def initUI(self):
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.layout = QVBoxLayout(self.centralWidget)
        self.layout.setContentsMargins(20, 20, 20, 20)

        # 添加背景图
        self.setStyleSheet("background-image: url('login.jpg');")

        self.welcomeLabel = QLabel('欢迎使用资源管理平台')
        self.welcomeLabel.setStyleSheet("font-size: 24px; font-weight: bold; color: white;")
        self.layout.addWidget(self.welcomeLabel)

        self.rsaButton = QPushButton('RSA加密')
        self.rsaButton.setStyleSheet("""
            font-size: 18px;
            background-color: #4CAF50;
            color: white;
            border-radius: 10px;
            padding: 10px;
        """)
        self.rsaButton.clicked.connect(self.openRsaEncryptionWindow)
        self.layout.addWidget(self.rsaButton)

        self.imageSteganographyButton = QPushButton('图像信息隐藏')
        self.imageSteganographyButton.setStyleSheet("""
            font-size: 18px;
            background-color: #2196F3;
            color: white;
            border-radius: 10px;
            padding: 10px;
        """)
        self.imageSteganographyButton.clicked.connect(self.openImageSteganographyWindow)
        self.layout.addWidget(self.imageSteganographyButton)

        # 添加工具栏按钮
        self.accountMenu = QMenu('账号管理', self)
        switchAccountAction = QAction('切换账号', self)
        switchAccountAction.triggered.connect(self.switchAccount)
        logoutAction = QAction('退出登录', self)
        logoutAction.triggered.connect(self.logout)
        loginAction = QAction('登录', self)
        loginAction.triggered.connect(self.open_login_window)

        self.accountMenu.addAction(switchAccountAction)
        self.accountMenu.addAction(logoutAction)
        self.accountMenu.addAction(loginAction)

        # 右上角显示登录信息
        # 工具栏
        self.toolBar = QToolBar('工具栏', self)
        self.addToolBar(self.toolBar)

        self.accountMenuButton = QAction('账户', self)
        self.accountMenuButton.setMenu(self.accountMenu)
        self.toolBar.addAction(self.accountMenuButton)

        self.current_user = 'admin'
        self.loginInfoLabel = QLabel()
        self.loginInfoLabel.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.update_login_info()
        self.toolBar.addWidget(self.loginInfoLabel)

        # 状态栏
        self.statusBar = self.statusBar()
        self.statusBar.showMessage('就绪')

        # 定时更新状态栏
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateStatusBar)
        self.timer.start(1000)  # 每隔1秒更新一次


    def openRsaEncryptionWindow(self):
        self.rsaWindow = RsaEncryptionWindow(self)
        self.rsaWindow.show()
        self.hide()

    def openImageSteganographyWindow(self):
        self.imageStegoWindow = ImageSteganographyWindow(self)
        self.imageStegoWindow.show()
        self.hide()

    def showWindow(self):
        self.show()

    def switchAccount(self):
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def logout(self):
        # 退出登录逻辑
        QMessageBox.information(self, '退出登录', '您已成功退出登录')
        self.loginInfoLabel.setText('登录用户: 未登录')

    def open_login_window(self):
        self.close()
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def update_login_info(self):
        self.loginInfoLabel.setText(f'登录用户: {self.current_user}')

    def updateStatusBar(self):
        currentTime = QDateTime.currentDateTime().toString('yyyy-MM-dd HH:mm:ss')
        self.statusBar.showMessage(f'当前时间: {currentTime} | 地区: 虚拟地区 | 页面署名: 云资源管理平台')


class RsaEncryptionWindow(QMainWindow):
    def __init__(self,mainWindow):
        super().__init__()
        self.mainWindow = mainWindow
        self.setWindowTitle('RSA加密')
        self.setGeometry(100, 100, 1000, 600)
        self.communicator = Communicator()
        self.private_key, self.public_key = self.generate_keys()
        self.initUI()

    def initUI(self):
        # 菜单栏
        self.menuBar = self.menuBar()
        fileMenu = self.menuBar.addMenu('文件')
        editMenu = self.menuBar.addMenu('编辑')
        viewMenu = self.menuBar.addMenu('视图')
        toolsMenu = self.menuBar.addMenu('工具')
        helpMenu = self.menuBar.addMenu('帮助')

        # 工具栏
        self.toolBar = QToolBar('工具栏', self)
        self.addToolBar(self.toolBar)

        # 添加工具栏按钮
        self.accountMenu = QMenu('账号管理', self)
        switchAccountAction = QAction('切换账号', self)
        switchAccountAction.triggered.connect(self.switchAccount)
        logoutAction = QAction('退出登录', self)
        logoutAction.triggered.connect(self.logout)
        loginAction = QAction('登录', self)
        loginAction.triggered.connect(self.open_login_window)

        self.accountMenu.addAction(switchAccountAction)
        self.accountMenu.addAction(logoutAction)
        self.accountMenu.addAction(loginAction)

        self.accountMenuButton = QAction('账户', self)
        self.accountMenuButton.setMenu(self.accountMenu)
        self.toolBar.addAction(self.accountMenuButton)

        # 状态栏
        self.statusBar = self.statusBar()
        self.statusBar.showMessage('就绪')

        # 定时更新状态栏
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateStatusBar)
        self.timer.start(1000)  # 每隔1秒更新一次

        # 右上角显示登录信息
        self.current_user = 'admin'
        self.loginInfoLabel = QLabel()
        self.loginInfoLabel.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.update_login_info()
        self.toolBar.addWidget(self.loginInfoLabel)

        # 创建中心部件和布局
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.layout = QVBoxLayout(self.centralWidget)

        # 创建左右区域
        self.leftWidget = QWidget()
        self.rightWidget = QWidget()
        self.splitter = QSplitter(Qt.Orientation.Horizontal, self)
        self.splitter.addWidget(self.leftWidget)
        self.splitter.addWidget(self.rightWidget)
        self.layout.addWidget(self.splitter)

        # 左边区域布局

        self.leftLayout = QVBoxLayout(self.leftWidget)
        self.setupLeftPanel()

        # 右边区域布局
        self.rightLayout = QVBoxLayout(self.rightWidget)
        self.setupRightPanel()

        self.backButton = QPushButton('返回')
        self.backButton.clicked.connect(self.goBack)
        self.layout.addWidget(self.backButton)

        # 创建文件类型选择下拉框
        self.fileTypeComboBox = QComboBox()
        self.fileTypeComboBox.addItems(
            ['文本文件 (.txt)', 'CSV 文件 (.csv)', '图片文件 (.png, .jpg)', '音频文件 (.mp3, .wav)', '文档文件 (.pdf)'])
        self.layout.addWidget(self.fileTypeComboBox)

        # 初始化文件路径
        self.currentFile = None

        # 新建文件动作
        self.newFileAction = QAction('新建', self)
        self.newFileAction.triggered.connect(self.newFile)
        fileMenu.addAction(self.newFileAction)

        # 打开文件动作
        self.openFileAction = QAction('打开', self)
        self.openFileAction.triggered.connect(self.openFile)
        fileMenu.addAction(self.openFileAction)

        # 保存文件动作
        self.saveFileAction = QAction('保存', self)
        self.saveFileAction.triggered.connect(self.saveFile)
        fileMenu.addAction(self.saveFileAction)

        # 退出程序动作
        self.exitAction = QAction('退出', self)
        self.exitAction.triggered.connect(self.close)
        fileMenu.addAction(self.exitAction)

    def setupLeftPanel(self):
        self.dataOld = QLabel("原始数据区域")
        self.leftLayout.addWidget(self.dataOld)

        self.textScrollArea = QScrollArea(self)
        self.textEdit = QTextEdit(self)

        self.textScrollArea.setWidget(self.textEdit)
        self.textScrollArea.setWidgetResizable(True)

        self.imageScrollArea = QScrollArea(self)
        self.imageLabel = QLabel(self)
        self.imageScrollArea.setWidget(self.imageLabel)
        self.imageScrollArea.setWidgetResizable(True)

        self.leftLayout.addWidget(self.textScrollArea)
        self.leftLayout.addWidget(self.imageScrollArea)

        # 初始时隐藏图片区域
        self.imageScrollArea.setVisible(False)

        # 添加一个按钮用于更新右侧区域
        self.updateButton = QPushButton('更新右侧内容', self)
        self.updateButton.clicked.connect(self.updateRightPanel)
        self.leftLayout.addWidget(self.updateButton)

        # 添加一个按钮用于加密
        self.RSAecodeButton = QPushButton('加密', self)
        self.RSAecodeButton.clicked.connect(self.RSAencode)
        self.leftLayout.addWidget(self.RSAecodeButton)



    def setupRightPanel(self):
        # 数据清理步骤显示区域
        self.dataCleaningSteps = QLabel("数据清理步骤显示区域")
        self.rightLayout.addWidget(self.dataCleaningSteps)

        # 添加其他必要的控件和布局
        self.resultScrollArea = QScrollArea(self)
        self.resultTextEdit = QTextEdit(self)

        self.resultScrollArea.setWidget(self.resultTextEdit)
        self.resultScrollArea.setWidgetResizable(True)

        self.ResultimageScrollArea = QScrollArea(self)
        self.ResultimageLabel = QLabel(self)
        self.ResultimageScrollArea.setWidget(self.ResultimageLabel)
        self.ResultimageScrollArea.setWidgetResizable(True)

        self.rightLayout.addWidget(self.resultScrollArea)
        self.rightLayout.addWidget(self.ResultimageScrollArea)

        # 初始时隐藏图片区域
        self.ResultimageScrollArea.setVisible(False)

        # 添加按钮用于清理数据
        self.cleanDataButton = QPushButton('清理数据', self)
        self.cleanDataButton.clicked.connect(self.cleanData)
        self.rightLayout.addWidget(self.cleanDataButton)

        # 添加按钮用于解密数据
        self.RSAnormalDataButton = QPushButton('解密', self)
        self.RSAnormalDataButton.clicked.connect(self.RSAnormal)
        self.rightLayout.addWidget(self.RSAnormalDataButton)

    def generate_keys(self):
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
        )
        public_key = private_key.public_key()
        return private_key, public_key

    def serialize_key(self, key):
        if isinstance(key, rsa.RSAPrivateKey):
            return key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption()
            )
        elif isinstance(key, rsa.RSAPublicKey):
            return key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )
        else:
            raise TypeError("Unsupported key type")

    def load_key(self, pem_data, key_type):
        if key_type == 'private':
            return load_pem_private_key(pem_data, password=None)
        elif key_type == 'public':
            return load_pem_public_key(pem_data)
        else:
            raise ValueError("Invalid key type")

    def encrypt_data(self, public_key, plaintext):
        ciphertext = public_key.encrypt(
            plaintext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        return ciphertext

    def decrypt_data(self, private_key, ciphertext):
        plaintext = private_key.decrypt(
            ciphertext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        return plaintext
    def RSAencode(self):
        plaintext = self.textEdit.toPlainText().encode('utf-8')
        if not plaintext:
            self.textEdit.setPlainText("No text to encrypt.")
            return
        # 加密
        ciphertext = self.encrypt_data(self.public_key, plaintext)
        self.textEdit.setPlainText(f'加密文本: {ciphertext.hex()}')
        pass
    def RSAnormal(self):
        try:
            ciphertext_str = self.resultTextEdit.toPlainText().replace('加密文本: ', '')
            ciphertext = bytes.fromhex(ciphertext_str)
            if not ciphertext:
                self.resultTextEdit.setPlainText("No ciphertext to decrypt.")
                return
            # 解密
            decrypted_plaintext = self.decrypt_data(self.private_key, ciphertext)
            self.resultTextEdit.setPlainText(f'解密文本: {decrypted_plaintext.decode("utf-8")}')
        except Exception as e:
            self.textEdit.setPlainText(f"Error: {str(e)}")
        pass


    def updateRightPanel(self):
        # 清空右侧区域
        self.resultTextEdit.clear()
        self.ResultimageLabel.clear()

        # 从左侧获取文字内容
        text_content = self.textEdit.toPlainText()
        if text_content.strip():  # 如果有文字内容
            self.resultTextEdit.setText(text_content)

        # 从左侧获取图片内容
        pixmap = self.imageLabel.pixmap()
        if pixmap:  # 如果有图片
            self.ResultimageLabel.setPixmap(pixmap)
            self.ResultimageScrollArea.setVisible(True)  # 显示图片区域
        else:  # 如果没有图片
            self.resultTextEdit.append("\n没有图片内容")
            self.ResultimageScrollArea.setVisible(False)  # 隐藏图片区域

        # # 刷新布局
        # self.rightLayout.update()

    def cleanData(self):
        # 数据清理逻辑示例
        self.resultTextEdit.clear()
        self.ResultimageLabel.clear()


    def newFile(self):
        fileType = self.fileTypeComboBox.currentText()
        fileName, _ = QFileDialog.getSaveFileName(self, '保存文件', '', self.getFileFilter(fileType))

        if fileName:
            self.currentFile = fileName
            if fileType == '文本文件 (.txt)' or fileType == 'CSV 文件 (.csv)':
                self.prepareTextEdit()
            elif fileType == '图片文件 (.png, .jpg)':
                self.prepareImageLabel()
            elif fileType == '音频文件 (.mp3, .wav)':
                self.prepareAudioFile(fileName)
            elif fileType == '文档文件 (.pdf)':
                self.prepareDocumentFile(fileName)
            elif fileType == 'Excel 文档 (.xlsx)':

                self.prepareExcelDocument(fileName)
        else:
            QMessageBox.warning(self, '错误', '未知的文件类型')

    def prepareTextEdit(self):
        self.textEdit.clear()
        self.textEdit.setVisible(True)
        self.imageLabel.setVisible(False)

    def prepareImageLabel(self):
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(True)
        self.imageLabel.setPixmap(QPixmap())  # 清空图片

    def prepareAudioFile(self, fileName):
        QMessageBox.information(self, '音频文件', f'已新建音频文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def prepareDocumentFile(self, fileName):
        QMessageBox.information(self, '文档文件', f'已新建文档文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def prepareExcelDocument(self, fileName):
        try:
            wb = openpyxl.Workbook()
            wb.save(fileName)
            QMessageBox.information(self, 'Excel 文档', f'已新建 Excel 文档: {fileName}')
            self.textEdit.setVisible(False)
            self.imageLabel.setVisible(False)
        except Exception as e:
            QMessageBox.warning(self, '保存文件失败', str(e))

    def getFileFilter(self, fileType):
        filters = {
            '文本文件 (.txt)': 'Text Files (*.txt)',
            'CSV 文件 (.csv)': 'CSV Files (*.csv)',
            '图片文件 (.png, .jpg)': 'Images (*.png *.jpg *.jpeg)',
            '音频文件 (.mp3, .wav)': 'Audio Files (*.mp3 *.wav)',
            '文档文件 (.pdf)': 'PDF Files (*.pdf)',
            'Excel 文档 (.xlsx)': 'Excel Documents (*.xlsx)',
        }
        return filters.get(fileType, 'All Files (*)')

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, '打开文件', '',
                                                  'Text Files (*.txt *.csv);;Images (*.png *.jpg *.jpeg);;PDF Files (*.pdf);;Audio Files (*.mp3 *.wav);;All Files (*)')
        if fileName:
            self.currentFile = fileName
            _, file_extension = fileName.rsplit('.', 1)
            file_extension = file_extension.lower()
            if file_extension in ['txt', 'csv']:
                self.open_text_or_csv_file(fileName)
            elif file_extension in ['png', 'jpg', 'jpeg']:
                self.open_image_file(fileName)
            elif file_extension == 'pdf':
                self.open_pdf_file(fileName)
            elif file_extension in ['mp3', 'wav']:
                self.open_audio_file(fileName)
            else:
                QMessageBox.information(self, '文件类型未支持', f'不支持的文件类型: {file_extension}')

    def saveFile(self):
        if self.currentFile:
            if self.currentFile.endswith('.csv'):
                try:
                    df = pd.read_csv(self.currentFile)
                    with open(self.currentFile, 'w', encoding='utf-8') as file:
                        file.write(self.textEdit.toPlainText())
                        df.to_csv(self.currentFile, index=False)
                except Exception as e:
                    QMessageBox.warning(self, '保存文件失败', str(e))
            elif self.currentFile.endswith('.txt'):
                try:
                    with open(self.currentFile, 'w', encoding='utf-8') as file:
                        file.write(self.textEdit.toPlainText())
                except Exception as e:
                    QMessageBox.warning(self, '保存文件失败', str(e))
            elif self.currentFile.endswith('.xlsx'):
                # 这里只是创建一个空文件，实际应用中可能需要从 textEdit 或其他来源获取数据
                wb = openpyxl.Workbook()
                wb.save(self.currentFile)
                QMessageBox.information(self, '保存文件', f'文件已保存: {self.currentFile}')
            elif self.currentFile.endswith('.png') or self.currentFile.endswith('.jpg') or self.currentFile.endswith(
                    '.jpeg'):
                # 使用 QFileDialog 选择保存位置
                # options = QFileDialog.Options()
                saveFilePath, _ = QFileDialog.getSaveFileName(self, "保存图像", "",
                                                              "图像文件 (*.png *.jpg *.jpeg);;所有文件 (*)",
                                                              )
                if saveFilePath:
                    try:
                        pixmap = self.imageLabel.pixmap()
                        if pixmap:
                            pixmap.save(saveFilePath)
                            QMessageBox.information(self, '保存文件', f'图像已保存: {saveFilePath}')
                        else:
                            QMessageBox.warning(self, '保存文件失败', '图像为空，无法保存')
                    except Exception as e:
                        QMessageBox.warning(self, '保存文件失败', str(e))
            else:
                QMessageBox.warning(self, '文件保存', '当前文件不支持保存操作')
        else:
            self.saveFileAs()

    def saveFileAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self, '保存文件', '',
                                                  'Text Files (*.txt *.csv);;All Files (*)')
        if fileName:
            self.currentFile = fileName
            self.saveFile()

    def open_text_or_csv_file(self, fileName):
        try:
            with open(fileName, 'r', encoding='utf-8') as file:
                if fileName.endswith('.csv'):
                    df = pd.read_csv(file)
                    self.textEdit.setText(df.to_string(index=False))
                else:
                    self.textEdit.setText(file.read())
            self.textScrollArea.setVisible(True)
            self.imageScrollArea.setVisible(False)
        except Exception as e:
            QMessageBox.warning(self, '打开文件失败', str(e))

    def open_image_file(self, fileName):
        try:
            pixmap = QPixmap(fileName)
            self.imageLabel.setPixmap(pixmap)
            self.imageScrollArea.setVisible(True)
            self.textScrollArea.setVisible(False)
        except Exception as e:
            QMessageBox.warning(self, '打开图片失败', str(e))

    def open_pdf_file(self, fileName):
        QMessageBox.information(self, 'PDF文件', f'已选择PDF文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def open_audio_file(self, fileName):
        QMessageBox.information(self, '音频文件', f'已选择音频文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def update_login_info(self):
        self.loginInfoLabel.setText(f'登录用户: {self.current_user}')

    def updateStatusBar(self):
        currentTime = QDateTime.currentDateTime().toString('yyyy-MM-dd HH:mm:ss')
        self.statusBar.showMessage(f'当前时间: {currentTime} | 地区: 虚拟地区 | 页面署名: 云资源管理平台')

    def switchAccount(self):
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def logout(self):
        # 退出登录逻辑
        QMessageBox.information(self, '退出登录', '您已成功退出登录')
        self.loginInfoLabel.setText('登录用户: 未登录')

    def open_login_window(self):
        self.close()
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def goBack(self):
        self.mainWindow.showWindow()  # 显示主窗口
        self.close()


class ImageSteganographyWindow(QMainWindow):
    def __init__(self,mainWindow):
        super().__init__()
        self.mainwindow = mainWindow
        self.setWindowTitle('图像信息隐藏')
        self.setGeometry(100, 100, 1000, 600)
        self.communicator = Communicator()
        self.image_file = None
        self.initUI()

    def initUI(self):
        # 菜单栏
        self.menuBar = self.menuBar()
        fileMenu = self.menuBar.addMenu('文件')
        editMenu = self.menuBar.addMenu('编辑')
        viewMenu = self.menuBar.addMenu('视图')
        toolsMenu = self.menuBar.addMenu('工具')
        helpMenu = self.menuBar.addMenu('帮助')

        # 工具栏
        self.toolBar = QToolBar('工具栏', self)
        self.addToolBar(self.toolBar)

        # 添加工具栏按钮
        self.accountMenu = QMenu('账号管理', self)
        switchAccountAction = QAction('切换账号', self)
        switchAccountAction.triggered.connect(self.switchAccount)
        logoutAction = QAction('退出登录', self)
        logoutAction.triggered.connect(self.logout)
        loginAction = QAction('登录', self)
        loginAction.triggered.connect(self.open_login_window)

        self.accountMenu.addAction(switchAccountAction)
        self.accountMenu.addAction(logoutAction)
        self.accountMenu.addAction(loginAction)

        self.accountMenuButton = QAction('账户', self)
        self.accountMenuButton.setMenu(self.accountMenu)
        self.toolBar.addAction(self.accountMenuButton)

        # 状态栏
        self.statusBar = self.statusBar()
        self.statusBar.showMessage('就绪')

        # 定时更新状态栏
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateStatusBar)
        self.timer.start(1000)  # 每隔1秒更新一次

        # 右上角显示登录信息
        self.current_user = 'admin'
        self.loginInfoLabel = QLabel()
        self.loginInfoLabel.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.update_login_info()
        self.toolBar.addWidget(self.loginInfoLabel)

        # 创建中心部件和布局
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.layout = QVBoxLayout(self.centralWidget)

        # 创建左右区域
        self.leftWidget = QWidget()
        self.rightWidget = QWidget()
        self.splitter = QSplitter(Qt.Orientation.Horizontal, self)
        self.splitter.addWidget(self.leftWidget)
        self.splitter.addWidget(self.rightWidget)
        self.layout.addWidget(self.splitter)

        # 左边区域布局

        self.leftLayout = QVBoxLayout(self.leftWidget)
        self.setupLeftPanel()

        # 右边区域布局
        self.rightLayout = QVBoxLayout(self.rightWidget)
        self.setupRightPanel()

        self.backButton = QPushButton('返回')
        self.backButton.clicked.connect(self.goBack)
        self.layout.addWidget(self.backButton)

        # 创建文件类型选择下拉框
        self.fileTypeComboBox = QComboBox()
        self.fileTypeComboBox.addItems(
            ['文本文件 (.txt)', 'CSV 文件 (.csv)', '图片文件 (.png, .jpg)', '音频文件 (.mp3, .wav)', '文档文件 (.pdf)'])
        self.layout.addWidget(self.fileTypeComboBox)

        # 初始化文件路径
        self.currentFile = None

        # 新建文件动作
        self.newFileAction = QAction('新建', self)
        self.newFileAction.triggered.connect(self.newFile)
        fileMenu.addAction(self.newFileAction)

        # 打开文件动作
        self.openFileAction = QAction('打开', self)
        self.openFileAction.triggered.connect(self.openFile)
        fileMenu.addAction(self.openFileAction)

        # 保存文件动作
        self.saveFileAction = QAction('保存', self)
        self.saveFileAction.triggered.connect(self.saveFile)
        fileMenu.addAction(self.saveFileAction)

        # 退出程序动作
        self.exitAction = QAction('退出', self)
        self.exitAction.triggered.connect(self.close)
        toolsMenu.addAction(self.exitAction)

    def setupLeftPanel(self):
        self.dataOld = QLabel("原始数据区域")
        self.leftLayout.addWidget(self.dataOld)

        self.textScrollArea = QScrollArea(self)
        self.textEdit = QTextEdit(self)

        self.textScrollArea.setWidget(self.textEdit)
        self.textScrollArea.setWidgetResizable(True)

        self.imageScrollArea = QScrollArea(self)
        self.imageLabel = QLabel(self)
        self.imageScrollArea.setWidget(self.imageLabel)
        self.imageScrollArea.setWidgetResizable(True)

        self.leftLayout.addWidget(self.textScrollArea)
        self.leftLayout.addWidget(self.imageScrollArea)

        # 初始时隐藏图片区域
        self.imageScrollArea.setVisible(False)

        # 添加一个按钮用于更新右侧区域
        self.updateButton = QPushButton('更新右侧内容', self)
        self.updateButton.clicked.connect(self.updateRightPanel)
        self.leftLayout.addWidget(self.updateButton)

        # 添加一个按钮用于加密
        self.RSAecodeButton = QPushButton('加密', self)
        self.RSAecodeButton.clicked.connect(self.RSAencode)
        self.leftLayout.addWidget(self.RSAecodeButton)

    def setupRightPanel(self):
        # 数据清理步骤显示区域
        self.dataCleaningSteps = QLabel("数据清理步骤显示区域")
        self.rightLayout.addWidget(self.dataCleaningSteps)

        # 添加其他必要的控件和布局
        self.resultScrollArea = QScrollArea(self)
        self.resultTextEdit = QTextEdit(self)

        self.resultScrollArea.setWidget(self.resultTextEdit)
        self.resultScrollArea.setWidgetResizable(True)

        self.ResultimageScrollArea = QScrollArea(self)
        self.ResultimageLabel = QLabel(self)
        self.ResultimageScrollArea.setWidget(self.ResultimageLabel)
        self.ResultimageScrollArea.setWidgetResizable(True)

        self.rightLayout.addWidget(self.resultScrollArea)
        self.rightLayout.addWidget(self.ResultimageScrollArea)

        # 初始时隐藏图片区域
        self.ResultimageScrollArea.setVisible(False)

        # 添加按钮用于清理数据
        self.cleanDataButton = QPushButton('清理数据', self)
        self.cleanDataButton.clicked.connect(self.cleanData)
        self.rightLayout.addWidget(self.cleanDataButton)

        # 添加按钮用于解密数据
        self.RSAnormalDataButton = QPushButton('解密', self)
        self.RSAnormalDataButton.clicked.connect(self.RSAnormal)
        self.rightLayout.addWidget(self.RSAnormalDataButton)

    def newFile(self):
        fileType = self.fileTypeComboBox.currentText()
        fileName, _ = QFileDialog.getSaveFileName(self, '保存文件', '', self.getFileFilter(fileType))

        if fileName:
            self.currentFile = fileName
            if fileType == '文本文件 (.txt)' or fileType == 'CSV 文件 (.csv)':
                self.prepareTextEdit()
            elif fileType == '图片文件 (.png, .jpg)':
                self.prepareImageLabel()
            elif fileType == '音频文件 (.mp3, .wav)':
                self.prepareAudioFile(fileName)
            elif fileType == '文档文件 (.pdf)':
                self.prepareDocumentFile(fileName)
            elif fileType == 'Excel 文档 (.xlsx)':

                self.prepareExcelDocument(fileName)
        else:
            QMessageBox.warning(self, '错误', '未知的文件类型')

    def prepareTextEdit(self):
        self.textEdit.clear()
        self.textEdit.setVisible(True)
        self.imageLabel.setVisible(False)

    def prepareImageLabel(self):
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(True)
        self.imageLabel.setPixmap(QPixmap())  # 清空图片

    def prepareAudioFile(self, fileName):
        QMessageBox.information(self, '音频文件', f'已新建音频文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def prepareDocumentFile(self, fileName):
        QMessageBox.information(self, '文档文件', f'已新建文档文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def prepareExcelDocument(self, fileName):
        try:
            wb = openpyxl.Workbook()
            wb.save(fileName)
            QMessageBox.information(self, 'Excel 文档', f'已新建 Excel 文档: {fileName}')
            self.textEdit.setVisible(False)
            self.imageLabel.setVisible(False)
        except Exception as e:
            QMessageBox.warning(self, '保存文件失败', str(e))

    def getFileFilter(self, fileType):
        filters = {
            '文本文件 (.txt)': 'Text Files (*.txt)',
            'CSV 文件 (.csv)': 'CSV Files (*.csv)',
            '图片文件 (.png, .jpg)': 'Images (*.png *.jpg *.jpeg)',
            '音频文件 (.mp3, .wav)': 'Audio Files (*.mp3 *.wav)',
            '文档文件 (.pdf)': 'PDF Files (*.pdf)',
            'Excel 文档 (.xlsx)': 'Excel Documents (*.xlsx)',
        }
        return filters.get(fileType, 'All Files (*)')

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, '打开文件', '',
                                                  'Text Files (*.txt *.csv);;Images (*.png *.jpg *.jpeg);;PDF Files (*.pdf);;Audio Files (*.mp3 *.wav);;All Files (*)')
        if fileName:
            self.currentFile = fileName
            _, file_extension = fileName.rsplit('.', 1)
            file_extension = file_extension.lower()
            if file_extension in ['txt', 'csv']:
                self.open_text_or_csv_file(fileName)
            elif file_extension in ['png', 'jpg', 'jpeg']:
                self.open_image_file(fileName)
            elif file_extension == 'pdf':
                self.open_pdf_file(fileName)
            elif file_extension in ['mp3', 'wav']:
                self.open_audio_file(fileName)
            else:
                QMessageBox.information(self, '文件类型未支持', f'不支持的文件类型: {file_extension}')

    def saveFile(self):
        if self.currentFile:
            if self.currentFile.endswith('.csv'):
                try:
                    df = pd.read_csv(self.currentFile)
                    with open(self.currentFile, 'w', encoding='utf-8') as file:
                        file.write(self.textEdit.toPlainText())
                        df.to_csv(self.currentFile, index=False)
                except Exception as e:
                    QMessageBox.warning(self, '保存文件失败', str(e))
            elif self.currentFile.endswith('.txt'):
                try:
                    with open(self.currentFile, 'w', encoding='utf-8') as file:
                        file.write(self.textEdit.toPlainText())
                except Exception as e:
                    QMessageBox.warning(self, '保存文件失败', str(e))
            elif self.currentFile.endswith('.xlsx'):
                # 这里只是创建一个空文件，实际应用中可能需要从 textEdit 或其他来源获取数据
                wb = openpyxl.Workbook()
                wb.save(self.currentFile)
                QMessageBox.information(self, '保存文件', f'文件已保存: {self.currentFile}')
            elif self.currentFile.endswith('.png') or self.currentFile.endswith('.jpg') or self.currentFile.endswith(
                    '.jpeg'):
                # 使用 QFileDialog 选择保存位置
                # options = QFileDialog.Options()
                saveFilePath, _ = QFileDialog.getSaveFileName(self, "保存图像", "",
                                                              "图像文件 (*.png *.jpg *.jpeg);;所有文件 (*)",
                                                              )
                if saveFilePath:
                    try:
                        pixmap = self.imageLabel.pixmap()
                        if pixmap:
                            pixmap.save(saveFilePath)
                            QMessageBox.information(self, '保存文件', f'图像已保存: {saveFilePath}')
                        else:
                            QMessageBox.warning(self, '保存文件失败', '图像为空，无法保存')
                    except Exception as e:
                        QMessageBox.warning(self, '保存文件失败', str(e))
            else:
                QMessageBox.warning(self, '文件保存', '当前文件不支持保存操作')
        else:
            self.saveFileAs()

    def saveFileAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self, '保存文件', '',
                                                  'Text Files (*.txt *.csv);;All Files (*)')
        if fileName:
            self.currentFile = fileName
            self.saveFile()

    def open_text_or_csv_file(self, fileName):
        try:
            with open(fileName, 'r', encoding='utf-8') as file:
                if fileName.endswith('.csv'):
                    df = pd.read_csv(file)
                    self.textEdit.setText(df.to_string(index=False))
                else:
                    self.textEdit.setText(file.read())
            self.textScrollArea.setVisible(True)
            self.imageScrollArea.setVisible(False)
        except Exception as e:
            QMessageBox.warning(self, '打开文件失败', str(e))

    def open_image_file(self, fileName):
        try:
            pixmap = QPixmap(fileName)
            self.imageLabel.setPixmap(pixmap)
            self.imageScrollArea.setVisible(True)
            self.textScrollArea.setVisible(False)
            self.image_file = fileName
        except Exception as e:
            QMessageBox.warning(self, '打开图片失败', str(e))

    def open_pdf_file(self, fileName):
        QMessageBox.information(self, 'PDF文件', f'已选择PDF文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def open_audio_file(self, fileName):
        QMessageBox.information(self, '音频文件', f'已选择音频文件: {fileName}')
        self.textEdit.setVisible(False)
        self.imageLabel.setVisible(False)

    def RSAencode(self):
        if self.image_file is None:
            QMessageBox.warning(self, '错误', '请先加载一张图片。')
            return

            # Read the image using the stored filename
        print(type(self.image_file))
        print(self.image_file)

        self.image_file = self.image_file.replace("/","\\")
        print(self.image_file)
        demo = cv2.imread(self.image_file, 0)
        r, c = demo.shape

        # Generate random key image
        key = np.random.randint(0, 256, size=(r, c), dtype=np.uint8)
        cv2.imwrite("./key.jpg", key)  # Save key image

        # Perform encryption
        encryption = cv2.bitwise_xor(demo, key)
        cv2.imwrite("./encrypted.jpg", encryption)  # Save encrypted image

        # Update UI to display encrypted image
        self.imageLabel.setPixmap(QPixmap("./encrypted.jpg"))
        self.imageScrollArea.setVisible(True)

    def RSAnormal(self):
        # 加载加密图像和密钥图像
        encryption = cv2.imread("./encrypted.jpg", 0)
        key = cv2.imread("./key.jpg", 0)

        # 执行解密
        decryption = cv2.bitwise_xor(encryption, key)
        cv2.imwrite("./decrypted.jpg", decryption)  # 保存解密后的图像

        # 显示解密图像
        self.ResultimageLabel.setPixmap(QPixmap("./decrypted.jpg"))
        self.ResultimageScrollArea.setVisible(True)

    def updateRightPanel(self):
        # 清空右侧区域
        self.resultTextEdit.clear()
        self.ResultimageLabel.clear()

        # 从左侧获取文字内容
        text_content = self.textEdit.toPlainText()
        if text_content.strip():  # 如果有文字内容
            self.resultTextEdit.setText(text_content)

        # 从左侧获取图片内容
        pixmap = self.imageLabel.pixmap()
        if pixmap:  # 如果有图片
            self.ResultimageLabel.setPixmap(pixmap)
            self.ResultimageScrollArea.setVisible(True)  # 显示图片区域
        else:  # 如果没有图片
            self.resultTextEdit.append("\n没有图片内容")
            self.ResultimageScrollArea.setVisible(False)  # 隐藏图片区域

        # # 刷新布局
        # self.rightLayout.update()

    def cleanData(self):
        # 数据清理逻辑示例
        self.resultTextEdit.clear()
        self.ResultimageLabel.clear()



    def update_login_info(self):
        self.loginInfoLabel.setText(f'登录用户: {self.current_user}')

    def updateStatusBar(self):
        currentTime = QDateTime.currentDateTime().toString('yyyy-MM-dd HH:mm:ss')
        self.statusBar.showMessage(f'当前时间: {currentTime} | 地区: 虚拟地区 | 页面署名: 云资源管理平台')

    def switchAccount(self):
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def logout(self):
        # 退出登录逻辑
        QMessageBox.information(self, '退出登录', '您已成功退出登录')
        self.loginInfoLabel.setText('登录用户: 未登录')

    def open_login_window(self):
        self.close()
        login_window = LoginWindow()
        login_window.exec()
        login_window.show()

    def goBack(self):
        self.mainwindow.showWindow()  # 显示主窗口
        self.close()

class RegistrationWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('账号注册中心')
        self.setGeometry(100, 100, 450, 650)  # 增加了宽度和高度以适应新元素

        # 设置背景图
        self.setStyleSheet("""
            QDialog {
                background-image: url('./register.jpg');
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
            }

            QLabel, QLineEdit, QCheckBox, QPushButton {
                margin: 20px;  # 组件之间的间距
            }

            QPushButton {
                background-color: #4CAF50;
                color: white;
                border-style: outset;
                border-width: 2px;
                border-radius: 10px;
                border-color: beige;
                font-size: 15px;
                padding: 6px;
            }

            QPushButton:hover {
                background-color: #45a049;
            }
        """)

        layout = QVBoxLayout()
        layout_user = QHBoxLayout()
        self.label_username = QLabel('Username:')
        self.textbox_username = QLineEdit()
        layout_user.addWidget(self.label_username)
        layout_user.addWidget(self.textbox_username)
        layout.addLayout(layout_user)

        self.label_password = QLabel('Password:')
        self.textbox_password = QLineEdit()
        self.textbox_password.setEchoMode(QLineEdit.EchoMode.Password)
        self.checkbox_show_password = QCheckBox('Show Password')
        self.checkbox_show_password.stateChanged.connect(self.toggle_password_visibility)
        layout_password = QHBoxLayout()
        layout_password.addWidget(self.label_password)
        layout_password.addWidget(self.textbox_password)
        layout_password.addWidget(self.checkbox_show_password)
        layout.addLayout(layout_password)

        self.label_confirm_password = QLabel('Confirm Password:')
        self.textbox_confirm_password = QLineEdit()
        self.textbox_confirm_password.setEchoMode(QLineEdit.EchoMode.Password)
        layout_confirm = QHBoxLayout()
        layout_confirm.addWidget(self.label_confirm_password)
        layout_confirm.addWidget(self.textbox_confirm_password)
        layout.addLayout(layout_confirm)
        self.button_register = QPushButton('Register')
        self.button_register.clicked.connect(self.register_account)
        layout.addWidget(self.button_register)

        # 设置按钮样式
        self.button_register.setStyleSheet("""
                    QPushButton {
                        background-color: #4CAF50;
                        color: white;
                        border-style: outset;
                        border-width: 2px;
                        border-radius: 10px;
                        border-color: beige;
                        font-size: 15px;
                        padding: 6px;
                    }
                    QPushButton:hover {
                        background-color: #45a049;
                    }
                """)

        self.setLayout(layout)



    def toggle_password_visibility(self):
        if  self.checkbox_show_password.isChecked():
            self.textbox_password.setEchoMode(QLineEdit.EchoMode.Normal)
            self.textbox_confirm_password.setEchoMode(QLineEdit.EchoMode.Normal)
        else:
            self.textbox_password.setEchoMode(QLineEdit.EchoMode.Password)
            self.textbox_confirm_password.setEchoMode(QLineEdit.EchoMode.Password)


    def register_account(self):
        username = self.textbox_username.text()
        password = self.textbox_password.text()
        confirm_password = self.textbox_confirm_password.text()

        if not username or not password or not confirm_password:
            QMessageBox.warning(self, 'Error', 'All fields are required!')
            return

        if password != confirm_password:
            QMessageBox.warning(self, 'Error', 'Passwords do not match!')
            return


        QMessageBox.information(self, 'Success', 'Account registered successfully!')
        self.close()

# 登录窗口类
class LoginWindow(QDialog):
    def __init__(self,main_window_class = MainWindow):
        super().__init__()
        self.main_window_class = main_window_class
        self.setWindowTitle('云资源管理平台')
        self.setGeometry(100, 100, 550, 450)

        # 样式调整，包括背景图和按钮样式
        # 设置背景图
        self.setStyleSheet("""
                   QDialog {
                        background-image: url('./login.jpg');
                        background-repeat: no-repeat;
                        background-position: center;
                        background-size: cover;
                    }

                    QLabel, QLineEdit, QCheckBox, QPushButton {
                        margin: 20px;
                    }

                    QPushButton {
                        background-color: #4CAF50;
                        color: white;
                        border-style: outset;
                        border-width: 2px;
                        border-radius: 10px;
                        border-color: beige;
                        font-size: 15px;
                        padding: 6px;
                    }

                    QPushButton:hover {
                        background-color: #45a049;
                    }
                """)

        label = QLabel("欢迎登录云资源管理平台！")

        # 用户名和密码输入
        self.label_username = QLabel('Username:')
        self.textbox_username = QLineEdit()
        self.label_password = QLabel('Password:')
        self.textbox_password = QLineEdit()
        self.textbox_password.setEchoMode(QLineEdit.EchoMode.Password)

        # 显示密码复选框
        self.checkbox_show_password = QCheckBox('Show Password')
        self.checkbox_show_password.stateChanged.connect(self.toggle_password_visibility)

        # 登录和注册按钮
        self.button_login = QPushButton('Login')
        self.button_login.clicked.connect(self.check_login)

        self.button_register = QPushButton('Register')
        self.button_register.clicked.connect(self.open_registration)

        # 布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(label)
        username_hbox = QHBoxLayout()
        username_hbox.addWidget(self.label_username)
        username_hbox.addWidget(self.textbox_username)
        main_layout.addLayout(username_hbox)
        password_hbox = QHBoxLayout()
        password_hbox.addWidget(self.label_password)
        password_hbox.addWidget(self.textbox_password)
        password_hbox.addWidget(self.checkbox_show_password)
        main_layout.addLayout(password_hbox)
        main_layout.addWidget(self.button_login)
        main_layout.addWidget(self.button_register)
        self.setLayout(main_layout)

    def toggle_password_visibility(self):
        if self.checkbox_show_password.isChecked():
            self.textbox_password.setEchoMode(QLineEdit.EchoMode.Normal)
        else:
            self.textbox_password.setEchoMode(QLineEdit.EchoMode.Password)

    def open_registration(self):
        reg_window = RegistrationWindow()
        reg_window.exec()

    def check_login(self):
        username = self.textbox_username.text()
        password = self.textbox_password.text()

        # 校验账密
        if username == 'admin' and password == 'password':
            QMessageBox.information(self, 'Success', 'Login Successful！')
            self.close()
            self.main_window = self.main_window_class()
            self.main_window.show()

        else:
            QMessageBox.warning(self, 'Error', 'Incorrect Username or Password！')

    def accept(self):
        # 假设登录成功
        self.login_success = True
        super().accept()

    def login_successful(self):
        return getattr(self, 'login_success', False)

def main():
    app = QApplication(sys.argv)
    window = LoginWindow()
    window.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()

